package DataConverters.DataReaders.readersImpl.defaultDataReader.LineReader;

import DataConverters.DataReaders.readersImpl.defaultDataReader.CharBuffer.CharBuffer;
import DataConverters.DataReaders.readersImpl.defaultDataReader.CharBuffer.EndOfBufferException;
import FileInformation.utils.EndOfLineType;

/**
 * Created by IntelliJ IDEA.
 * User: Nobody
 * Date: 25.04.11
 * Time: 00:03
 * To change this template use File | Settings | File Templates.
 */
public class LineReader {
    private final LineBuilder lineBuilder = new LineBuilder();


    public char[] readLine(CharBuffer buffer, EndOfLineType endLineType) throws EndOfBufferException {
        int i = setPosAtTheEndOfLine(buffer, endLineType);
        lineBuilder.append(buffer.getRemainingChars(i));
        ignoreEndOfLine(buffer,endLineType);
        char[] outputArray  = lineBuilder.toCharArray();
        lineBuilder.clear();
        return outputArray;
    }

    void ignoreEndOfLine(CharBuffer buffer, EndOfLineType endOfLineType) {
        if (endOfLineType == EndOfLineType.WINDOWS)
            buffer.incrementPosition(2);
        if (endOfLineType == EndOfLineType.LINUX)
            buffer.incrementPosition(1);
    }

    private int setPosAtTheEndOfLine(CharBuffer buffer, EndOfLineType typeOfEndLine) throws EndOfBufferException {
        int i = buffer.position();

        if (typeOfEndLine == EndOfLineType.WINDOWS) {
            while (i < buffer.limit() && buffer.get(i) != '\r') {
                ++i;
                if (i >= buffer.limit()) {
                    lineBuilder.append(buffer);
                    throw new EndOfBufferException();
                }
                if (buffer.get(i) == '\n')
                    break;
            }
            ++i;
        } else if (typeOfEndLine == EndOfLineType.LINUX) {
            while (i < buffer.limit() && buffer.get(i) != '\n') {
                ++i;
            }

            if (i >= buffer.limit()) {
                lineBuilder.append(buffer);
                throw new EndOfBufferException();
            }
            ++i;
        }
        return i;
    }


}
